const app = getApp()
import {urls} from '../../../utils/urls'
let _this;
Page({
  data: {
    id : '',
    lou:'',
    num:'',
    is_default:false,
    show: false,
    columns: [],
    new_lou:'',
    addr_point_id : 1
  },
  onLoad: function (options) {
    _this = this
    if(options.data!="undefined"){
      let addr = JSON.parse(options.data)
      let addr_list =addr.addr.split('-')
      console.log(addr_list);
      _this.setData({
        lou:addr_list[0],
        num:addr_list[1],
        is_default:addr.is_default,
        id:addr.id
      })
    }
    this.get_addr_piont_list()
  },
  change_default(e){
    this.setData({
      is_default : e.detail.value
    })
  },
  num_input(e){
    this.setData({
      num: e.detail.value
    })
  },
  showPopup(){
    this.setData({
      show:true
    })
  },
  onChange(event) {
    // console.log(event);
    const {value, index } = event.detail;
    _this.setData({
      new_lou : value
    })
  },
  onCancel(){
    _this.setData({
      new_lou: _this.data.lou,
      show: false
    })
  },
  onConfirm(){
    _this.setData({
      lou : _this.data.new_lou,
      show: false
    })
  },
  get_addr_piont_list(){
    app.http('GET',urls.addrpoint,{'type':1,'school':wx.getStorageSync('school').id},
    function(res){
      let addr_point_list = res.results
      let  columns = []
      let columns_dict = {}
      for(let i in addr_point_list){
        columns.push(addr_point_list[i].name)
      }
      for (let i in addr_point_list){
        columns_dict[addr_point_list[i].name] = addr_point_list[i].id
      }
      _this.setData({
        columns: columns,
        columns_dict: columns_dict
      })
    })
  },
  submit(){
    if(this.data.lou == ''){
      wx.showToast({
        title: '请选择楼栋',
        icon:'none'
      })
    }else if(this.data.num == ''){
      wx.showToast({
        title: '请输入门牌号',
        icon:'none'
      })
    }else{
      wx.showLoading({
        title: '保存中',
        task:true
      })
      let method = 'POST'
      let formData = {
        addr: this.data.lou + '-' + this.data.num,
        is_default: this.data.is_default,
        addr_point : this.data.columns_dict[this.data.lou],
        user:[wx.getStorageSync("user").id,]
      }
      if(this.data.id){
        method = 'PUT'
        formData.id = this.data.id
      }
      // console.log(formData);
      app.http(method,urls.addr,formData,
        function(res){
        wx.hideLoading()
        if(res.code == 100){
          wx.showToast({
            title: '保存成功',
            mask:true
          })
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            })
          }, 800)
          }else{
            wx.hideLoading()
            wx.showToast({
              title: '保存失败',
              mask:true
            })
          }
      })
    }
  },
})